﻿using System;
using System.Linq.Expressions;
using FluentExport.CSVExport.Interfaces;

namespace FluentExport.CSVExport
{
    public class CSVExportHelper : ICSVExportHelper
    {
        #region Methods

        public string GetPropertyName<TSource>(Expression<Func<TSource, object>> source)
        {
            var body = source.Body as MemberExpression;

            if (body == null)
            {
                var ubody = (UnaryExpression)source.Body;
                body = ubody.Operand as MemberExpression;
                if (body != null) return body.Member.Name;

            }
            if (body != null) return body.Member.Name;

            throw new InvalidOperationException("Invalid property expression.");
        }

        public string FormatValue(object value)
        {
            var stringValue = value.ToString();
            return stringValue.Contains(",") ? String.Format("\"{0}\"", stringValue) : stringValue;
        }

        #endregion
    }
}
